import { LOGIN_SUCCESS, LOGOUT_SUCCESS, GEN_ACCESS_ROUTES } from "../actions/action-type"
// import { generateAccessRoutes } from "../utils/permission"

// 根据 token 数据获取用户初始菜单数据
// let menus = JSON.parse(localStorage.getItem('menus') || sessionStorage.getItem('menus')) || []
// 生成前端路由数组
// menus = generateAccessRoutes(menus)

// 初始状态值
const initialState = {
  username: localStorage.getItem('username') || sessionStorage.getItem('username') || '',
  avatarUrl: localStorage.getItem('avatarUrl') || sessionStorage.getItem('avatarUrl') || '',
  token: localStorage.getItem('token') || sessionStorage.getItem('token') || '',
  menus: []  // 访问的路由数组
}

/**
 * reducer 纯函数
 * @param {*} state 状态
 * @param {*} param1 action对象
 * @returns 返回新的 state 状态
 */
const reducer = (state = initialState, { type, payload }) => {
  switch (type) {
    case LOGIN_SUCCESS: // 登录成功，合并状态数据
      return { ...state, ...payload }
    case GEN_ACCESS_ROUTES: // 生成访问路由
      return {
        ...state,
        ...payload
      }
    case LOGOUT_SUCCESS: // 退出成功
      return {
        username: '',
        avatarUrl: '',
        token: '',
        menus: []
      }
    default:
      return state
  }
}

export default reducer
